/**
 * 
 */
package com.et114.core.action;

//import java.io.UnsupportedEncodingException;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.File;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import org.springframework.util.Assert;

import com.et114.components.acegi.Constants;
import com.et114.core.common.AppContext;
import com.et114.core.resources.FrameworkMessageManager;
import com.et114.core.utility.IOTools;
import com.et114.core.utility.StringPool;
import com.et114.core.utility.ThreadSynchronizer;

/*
 * @author guanhw
 */
abstract public class AbstractUploadAction extends BaseAction {
	protected Log	logger	= LogFactory.getLog ( this.getClass ( ) );
	private int restrictfs = AppContext.getFrameWorkPropertiesBean ( ).getUploadMaxSize ( ) ;
	
	public final ActionForward toExecute ( ActionMapping mapping ,
										   ActionForm form , 
										   HttpServletRequest request ,
			                               HttpServletResponse response ) throws Exception {
		ThreadSynchronizer.threadEnter ( );
		ActionForward to = null ; 
		try {
			to = upload ( mapping , form , request , response );
		}/*
		catch ( Exception ex ) {
			throw new Exception( ex )  ;
		}*/
		finally {
			ThreadSynchronizer.threadExit ( );
		}
		return to;
	}
	
	protected void uploadv2 ( FormFile formFile , HttpServletRequest request , String path  ) throws Exception { 
		uploadv2 ( formFile , request , path , null  ) ; 
	}
	
	protected void setRestrictfs ( int restrictfs ) {
		this.restrictfs = restrictfs;
	}

	/**
	 * rpwfn real path:must with 'AppContext.getFrameWorkPropertiesBean ( ).getUploadServerPath ( )'
	 * @param formFile
	 * @param request
	 * @param rpwfn
	 * @throws Exception
	 */
	protected void uploadFilev2 ( FormFile formFile , HttpServletRequest request , String rpwfn  ) throws Exception { 
		// 
		InputStream in = null;
		OutputStream out = null;
		try {
			
			logger.info ( "upload file " + formFile.getFileName ( ) + " size is :"  + formFile.getFileSize ( ) ) ;
			if ( restrictfs < formFile.getFileSize ( ) ) 
				throw new Exception ( Constants.SYS_EXP_K + FrameworkMessageManager.get ( ).getMessage ( "upload.file.size.val" , request.getLocale ( ) ) + ( restrictfs / 1024 ) + "KB"  ) ; 
			
			Assert.notNull ( rpwfn ) ; 
			//AppContext.getFrameWorkPropertiesBean ( ).getUploadServerPath ( );
			if ( !rpwfn.startsWith (  StringPool.FORWARD_SLASH ) ) rpwfn = StringPool.FORWARD_SLASH  + rpwfn ; 
			String serverPath = getServlet ( ).getServletContext ( ).getRealPath ( rpwfn ) ; 
			String path = serverPath.substring ( 0 , serverPath.lastIndexOf ( File.separator )  ) ;
			File file = new File( path ) ; 
			if ( !file.exists ( )  ) file.mkdirs ( ) ; 
			file = new File( serverPath ) ; 
			if ( !file.exists ( ) ) file.createNewFile ( ) ;
			
			in = formFile.getInputStream ( ) ; 
			out = new FileOutputStream( serverPath ) ;
			IOTools.flow ( in , out ) ; 
		} catch ( Exception e ) {
			logger.error ( e.getMessage() ,  e  ) ;
			throw new Exception( e.getMessage ( ) , e ) ;
		} finally {
			try {
				if ( in != null ) in.close();
				if ( out != null ) out.close();
				if ( formFile != null ) formFile.destroy();
			} catch ( Exception ex ) {
				logger.error ( ex.getMessage() ,  ex  ) ;
			}
		}		
	}
	
	protected void uploadv2 ( FormFile formFile , HttpServletRequest request , String path , String newFileName ) throws Exception {
		Assert.notNull ( formFile ) ; 
		Assert.notNull ( formFile.getFileName ( ) ) ; 
		if ( path == null ) path = StringPool.FORWARD_SLASH ; 
		path = path.trim ( ) ;
		if ( !path.endsWith ( StringPool.FORWARD_SLASH ) ) path += StringPool.FORWARD_SLASH ; 
		if ( !path.startsWith ( StringPool.FORWARD_SLASH ) ) path = StringPool.FORWARD_SLASH + path ;
		String fileName = formFile.getFileName ( ) ; 
		if ( fileName.indexOf ( StringPool.PERIOD ) > 0 && newFileName != null && !"".equals ( newFileName.trim ( ) ) )
			newFileName = newFileName +  fileName.substring ( fileName.lastIndexOf ( StringPool.PERIOD ) ) ;
		fileName = ( ( newFileName != null && !"".equals ( newFileName.trim ( ) ) ) ? newFileName : formFile.getFileName ( ) ) ; 
		path += fileName ;
		uploadFilev2( formFile , request , path ) ;
	}
	
	
	protected void uploadv1 ( FormFile formFile , HttpServletRequest request , String path  ) throws Exception { 
		uploadv1 ( formFile , request , path , null  ) ; 
	}
	
	protected void uploadv1 ( FormFile formFile , HttpServletRequest request , String path , String newFileName ) throws Exception {
		// 
		InputStream in = null;
		OutputStream out = null;
		try {
			//int maxSize = AppContext.getFrameWorkPropertiesBean ( ).getUploadMaxSize ( );
			
			if ( formFile.getFileName ( ) != null && newFileName != null && !"".equals ( newFileName ) ) {
				String fileName = formFile.getFileName ( ) ; 
				if ( fileName.indexOf ( StringPool.PERIOD ) > 0  )
					newFileName = newFileName +  fileName.substring ( fileName.lastIndexOf ( StringPool.PERIOD ) ) ;
				newFileName = fileName  ;
			}
			
			logger.info ( "upload file " + formFile.getFileName ( ) + " size is :"  + formFile.getFileSize ( ) ) ;
			if ( restrictfs < formFile.getFileSize ( ) ) {
				throw new Exception ( Constants.SYS_EXP_K + FrameworkMessageManager.get ( ).getMessage ( "upload.file.size.val" , request.getLocale ( ) ) + ( restrictfs / 1024 ) + "KB" ) ; 
			}
			
			String serverPath = AppContext.getFrameWorkPropertiesBean ( ).getUploadServerPath ( );
			if ( path != null && !"".equals ( path.trim ( ) ) ) {
				path = path.trim ( ) ;
				if ( path .length ( ) > 1 && path.endsWith ( "/" ) ) path = path.substring ( 0 , path.length ( ) -1 ) ;
				if ( !path .startsWith ( "/" ) ) path = "/" + path ;
				serverPath = getServlet ( ).getServletContext ( ).getRealPath ( path ) ; 
			}
			else {
				if ( serverPath != null ) {
					serverPath = getServlet ( ).getServletContext ( ).getRealPath ( serverPath ) ; 
				}				
			}
			   
			File file = new File( serverPath ) ; 
			if ( !file.exists ( )  ) {
				file.mkdirs ( ) ; 
			}
			
			String fileName = ( ( newFileName != null && ! "".equals ( newFileName ) ) ? newFileName : formFile.getFileName ( ) ) ; 
			file = new File ( serverPath + File.separator + fileName );
			if ( !file.exists ( )  ) {
				file.createNewFile ( );
			}
			
			in = formFile.getInputStream ( ) ; 
			out = new FileOutputStream( file ) ;
			IOTools.flow ( in , out ) ; 
		} catch ( Exception e ) {
			logger.error ( e.getMessage() ,  e  ) ;
			throw new Exception( e.getMessage ( ) , e ) ;
		} finally {
			try {
				if ( in != null ) in.close();
				if ( out != null ) out.close();
				if ( formFile != null ) formFile.destroy();
			} catch ( Exception ex ) {
				logger.error ( ex.getMessage() ,  ex  ) ;
			}
		}
	}	
	
	abstract protected ActionForward upload(  ActionMapping mapping ,
			ActionForm form , HttpServletRequest request ,
			HttpServletResponse response )  throws Exception  ;
	
	

}
